// Fill out your copyright notice in the Description page of Project Settings.


#include "MyBPAsyncTaskActionBase.h"

UMyBPAsyncTaskActionBase* UMyBPAsyncTaskActionBase::WaitTickTestActorCounter(UObject* WorldContextObject, ATickTestActor* Actor, int32 TargetCounter)
{
    UMyBPAsyncTaskActionBase* Node = NewObject<UMyBPAsyncTaskActionBase>();
    (new FAutoDeleteAsyncTask<MyAsyncTask>(Node, Actor, TargetCounter))->StartBackgroundTask();
    UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u wait TargetCounter(%d) begin."), __LINE__, TargetCounter);
    return Node;
}

void MyAsyncTask::DoWork()
{
    while (IsValid(Actor) && IsValid(Node))
    {
        if (Actor->Counter >= TargetCounter)
        {
            UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u wait TargetCounter(%d) success. Current Counter=[%d]."), __LINE__, TargetCounter, Actor->Counter);
            AsyncTask(ENamedThreads::GameThread, [=]()
            {
                Node->OnSuccess.Broadcast(Actor->Counter);
            });
            return;
        }
        UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u waiting TargetCounter(%d)... Current Counter=[%d]."), __LINE__, TargetCounter, Actor->Counter);
        FPlatformProcess::Sleep(0.01f);
    }
    UE_LOG(LogTemp, Log, TEXT(__FUNCTION__"@%u wait fail. Actor is invalid."), __LINE__);
    AsyncTask(ENamedThreads::GameThread, [=]()
    {
        Node->OnFail.Broadcast(-1);
    });
}
